<template>
  <div class="container mx-auto px-4 py-8">
    <h2 class="text-2xl font-bold mb-6">我的订单</h2>

    <!-- 订单状态标签页 -->
    <el-tabs v-model="activeStatus" class="mb-6" @tab-click="handleTabChange">
      <el-tab-pane label="全部" name="all" />
      <el-tab-pane label="待付款" name="pending" />
      <el-tab-pane label="待发货" name="processing" />
      <el-tab-pane label="待收货" name="shipped" />
      <el-tab-pane label="已完成" name="completed" />
    </el-tabs>

    <!-- 订单列表 -->
    <div class="space-y-4">
      <el-empty
        v-if="!filteredOrders.length"
        description="暂无订单"
      >
        <el-button type="primary" @click="router.push('/products')">
          去购物
        </el-button>
      </el-empty>

      <el-card v-for="order in filteredOrders" :key="order.id" class="order-card">
        <div class="flex justify-between items-center mb-4">
          <span class="text-gray-500">订单号：{{ order.orderNo }}</span>
          <span class="text-primary">{{ getOrderStatusText(order.status) }}</span>
        </div>

        <div class="space-y-4">
          <div v-for="item in order.orderItems" :key="item.id" class="flex gap-4">
            <img :src="item.productImage" class="w-20 h-20 object-cover rounded" />
            <div class="flex-1">
              <h4 class="font-medium">{{ item.productName }}</h4>
              <p class="text-gray-500">¥{{ item.price }} × {{ item.quantity }}</p>
              <!-- 已完成状态的商品评价按钮 -->
              <div v-if="order.status === 'completed'" class="mt-2">
                <el-button
                  type="primary"
                  plain
                  size="small"
                  :disabled="item.isReviewed"
                  @click="handleReview(order, item)"
                >
                  {{ item.isReviewed ? '已评价' : '评价' }}
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <div class="flex justify-between items-center mt-4 pt-4 border-t">
          <span>总计：<span class="text-xl text-primary font-bold">¥{{ order.totalAmount }}</span></span>
          <div class="space-x-2">
            <!-- 待付款状态 -->
            <template v-if="order.status === 'pending'">
              <el-button type="primary" @click="handlePay(order)">
                立即支付
              </el-button>
              <el-button @click="handleCancelOrder(order)">
                取消订单
              </el-button>
            </template>

            <!-- 待发货状态 -->
            <template v-if="order.status === 'processing'">
              <el-button type="info" disabled>
                等待商家发货
              </el-button>
            </template>

            <!-- 待收货状态 -->
            <template v-if="order.status === 'shipped'">
              <el-button type="success" @click="handleConfirm(order)">
                确认收货
              </el-button>
              <el-button @click="handleTracking(order)">
                查看物流
              </el-button>
            </template>

            <!-- 已完成状态 -->
            <template v-if="order.status === 'completed'">
              <el-button @click="handleBuyAgain(order)">
                再次购买
              </el-button>
            </template>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  getOrders,
  buyAgain,
  payOrder,
  cancelOrder,
  confirmOrder
} from '@/api/orders'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const activeStatus = ref('all')
const orders = ref([])

// 获取地址栏参数
const query = new URLSearchParams(window.location.search)
if (query.has('status')) {
  activeStatus.value = query.get('status')
}

const getOrderStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待付款'
    case 'processing':
      return '待发货'
    case 'shipped':
      return '待收货'
    case 'completed':
      return '已完成'
    case 'cancelled':
      return '已取消'
    default:
      return '未知状态'
  }
}

// 获取订单数据
const fetchOrders = async () => {
  try {
    const {data} = await getOrders(activeStatus.value)
    orders.value = data
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  }
}

// 根据状态筛选订单
const filteredOrders = computed(() => {
  if (activeStatus.value === 'all') {
    return orders.value
  }
  return orders.value.filter(order => order.status === activeStatus.value)
})

// 标签页切换
const handleTabChange = (tab) => {
  activeStatus.value = tab.props.name
  router.push({
    query: {
      status: activeStatus.value
    }
  })
  fetchOrders()
}

// 支付订单
const handlePay = async (order) => {
  try {
    await payOrder(order.id)
    ElMessage.success('支付成功')
    await fetchOrders() // 刷新订单列表
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 取消订单
const handleCancelOrder = (order) => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await cancelOrder(order.id)
      ElMessage.success('订单取消成功')
      await fetchOrders() // 刷新订单列表
    } catch (error) {
      ElMessage.error(error.message)
    }
  })
}

// 确认收货
const handleConfirm = (order) => {
  ElMessageBox.confirm('确认已收到商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      await confirmOrder(order.id)
      ElMessage.success('确认收货成功')
      await fetchOrders() // 刷新订单列表
    } catch (error) {
      ElMessage.error('确认收货失败')
    }
  })
}

// 查看物流
const handleTracking = (order) => {
  router.push({
    path: '/tracking',
    query: { orderNo: order.orderNo }
  })
}

// 评价订单
const handleReview = (order, item) => {
  // 检查是否已评价
  const isReviewed = item.isReviewed
  if (isReviewed) {
    ElMessage.warning('该商品已评价')
    return
  }

  router.push({
    path: `/orders/${order.id}/items/${item.id}/review`,
    query: {
      name: item.name,
      image: item.image,
      price: item.price,
      quantity: item.quantity
    }
  })
}

// 再次购买
const handleBuyAgain = async (order) => {
  try {
    const cartItems = await buyAgain(order.id)
    console.log('添加到购物车:', cartItems)
    ElMessage.success('已添加到购物车')
    router.push('/cart')
  } catch (error) {
    ElMessage.error('添加到购物车失败')
  }
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-card {
  transition: all 0.3s ease;
}
.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>
